package com.yhk.wuchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import java.net.InetSocketAddress;
import java.util.Optional;

/**
 * 创建自定义握手处理器，从连接中获取token
 * 如果用户连接中携带token，则将token存放在channel中
 */
public class MyHeaderCollectHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request=(HttpRequest)msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
            Optional<String> token = Optional.of(urlBuilder).map(UrlBuilder::getQuery)
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            if(token.isPresent()){
                //将连接中token存放在channel中
                NettyUtil.setAttr(ctx.channel(),NettyUtil.TOKEN,token.get());
            }
            request.setUri(urlBuilder.getPath().toString());
            //获取用户ip
            String ip = request.headers().get("X-Real-IP");//从nginx中获取用户ip
            if(StrUtil.isBlank(ip)){
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();//获取主机ip
            }
            //保存到channel附件
            NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
            //处理器只需要使用一次
            ctx.pipeline().remove(this);
        }
        //传递给下一个处理器
        ctx.fireChannelRead(msg);
    }
}
